const express = require('express')
const expect = require('../../extensions/expect')
const db = require('../../db/db')


const router = express.Router()

router.get('/user/signin', (req, res) => {
    res.render('user/signin')
})

router.post('/api/user/signin', (req, res) => {
    expect(req.body.account).toMatch(/^(admin)|([\u4e00-\u9fa5]{2,6})$/).error('帐号是2~6个中文字符！')
    expect(req.body.password).toMatch(/^.{6,20}$/).error('密码需要6~20个字符！')

    var filter = {
        account: req.body.account,
        password: req.body.password
    }

    db.User.Model.find(filter)
        .select('account photo createTime ip')
        .exec()
        .then(models => {
            if (models.length > 0) {
                res.cookie('user', db.toData(models[0]))
                res.apiSuccess('登录成功！')
            }
            else {
                res.apiMessage('帐号或密码错误！')
            }
        })
        .catch(err => {
            res.apiError(err)
        })
})


module.exports = router